package org.xacmlauth.dao.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xacmlauth.dao.PolicyDAO;
import org.xacmlauth.dto.PolicyDTO;

public class JDBCPolicyDAO extends AbstractDAO implements PolicyDAO{
	
	private static final Log LOG = LogFactory.getLog(JDBCPolicyDAO.class);

	@Override
	public boolean registerPolicy(List<PolicyDTO> policies){
		boolean status = false;
		Connection con = null;
		try {
			con = getConnection();
			PolicyDTO policy = policies.get(0);
			
			PreparedStatement pStmt = con.prepareStatement("INSERT INTO POLICY(CLIENT_ID,CONTENT, NAME, DESCRIPTION) VALUES (?, ?, ?, ?) ");
			pStmt.setInt(1, Integer.parseInt(policy.getClientId()));
			pStmt.setString(2, policy.getContent());
			pStmt.setString(3, policy.getName());
			pStmt.setString(4, policy.getDescription());
			status = pStmt.execute();
			con.commit();
			status = true;
		} catch (Exception e) {
			LOG.error("Register Policy Error ", e);
		} finally {
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					LOG.error("Connection Close Error", e);
				}
			}
		}
		
		return status;
	}

	@Override
	public List<PolicyDTO> findPolicies(String cleintID) throws Exception {
		Connection con = null;
		List<PolicyDTO> policyList = new ArrayList<PolicyDTO>();
		try {
			con = getConnection();
			PreparedStatement pStmt = con.prepareStatement("SELECT CONTENT, NAME, DESCRIPTION, CLIENT_ID FROM POLICY WHERE CLIENT_ID = ?");
			pStmt.setInt(1, Integer.parseInt(cleintID));
			ResultSet rs = pStmt.executeQuery();
			
			while(rs.next()){
				PolicyDTO policy = new PolicyDTO();
				policy.setClientId(String.valueOf(rs.getInt("CLIENT_ID")));
				policy.setContent(rs.getString("CONTENT"));
				policy.setName(rs.getString("NAME"));
				policy.setDescription(rs.getString("DESCRIPTION"));
				policyList.add(policy);
			}
		} catch (Exception e) {
			LOG.error("Find Policies Error ", e);
		} finally {
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					LOG.error("Connection Close Error", e);
				}
			}
		}
		
		return policyList;
	}

	@Override
	public boolean deletePolicies(String clientID) throws Exception {
		Connection con = null;
		boolean status = false;

		try {
			con = getConnection();
			PreparedStatement pStmt = con.prepareStatement("DELETE FROM POLICY WHERE CLIENT_ID = ?");
			pStmt.setInt(1, Integer.parseInt(clientID));
			
			pStmt.execute();
			con.commit();
			status = true;
			
		} catch (Exception e) {
			LOG.error("Find Policies Error ", e);
		} finally {
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					LOG.error("Connection Close Error", e);
				}
			}
		}
		
		return status;
	}
	
	

}
